package com.stwyj.sbd.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.stwyj.sbd.common.AppErrors;
import com.stwyj.sbd.config.exception.ResultErrorException;
import com.stwyj.sbd.entity.domain.UserCollection;
import com.stwyj.sbd.entity.dto.UserDto;
import com.stwyj.sbd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 *<p>
 * 测试demo
 *</p>
 *
 * @author stwyj
 * @since 2018/11/30
 */
@RestController
@RequestMapping("hello")
@Slf4j
public class HelloController {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 返回用户信息
     * @param name 用户名称
     * @return 用户信息
     */
    @GetMapping("user/get")
    public UserDto sayHello(String name) {
        // lombok logback注解测试
        log.info("param name is: {}", name);
        return UserDto.builder().id(123).name(name).build();
    }

    /**
     * 异常返回demo
     * @return 无
     * @throws ResultErrorException
     */
    @GetMapping("resultError")
    public String resultError() throws ResultErrorException {
        throw new ResultErrorException(AppErrors.ERROR_NO_AUTH);
    }

    /**
     * 验证demo
     * @param userDto userDto 用户信息
     * @return 用户信息
     */
    @PostMapping("validate")
    public UserDto validate(@Valid @RequestBody UserDto userDto) {
        return userDto;
    }

    /**
     * service test
     * @param id id
     * @param name 名称
     * @return 用户信息
     */
    @GetMapping("service")
    public UserDto serviceTest(@RequestParam Integer id, @RequestParam  String name) {
        return userService.getUser(UserDto.builder().id(id).name(name).build());
    }

    /**
     * 重试demo
     * XXXXXX@return 用户信息
     */
    @GetMapping("retry")
    public void updateUser() {
        userService.updateUser();
    }

    /**
     * 用户新增
     */
    @GetMapping("userAdd")
    public void userAdd() {
        com.stwyj.sbd.entity.po.User user = new com.stwyj.sbd.entity.po.User();
        user.setAge(1);
        user.setName("a");

        userService.insertUser(user);
    }

    /**
     * 分页查询用户信息
     * @return 用户信息集合
     */
    @GetMapping("getUser")
    public Page<com.stwyj.sbd.entity.po.User> getUser() {
        return  userService.getUsers();
    }

    @GetMapping("mongoList")
    public org.springframework.data.domain.Page<UserCollection> mongoList() {

        return userService.mongoList();
    }

    /**
     * redis测试
     * @return 对于key——redis_test进行原子自增操作，返回结果
     */
    @GetMapping("redisTest")
    public Long redisTest() {
        return stringRedisTemplate.opsForValue().increment("redis_test", 1L);
    }
}
